﻿@inject ComponentApplicationState AppState
@inject PreserveStateService PreserveService
@using System.Text

<p id="@($"state-{State}")">@State: @_state</p>

@if (_restored)
{
    <p id="@($"restored-{State}")">true</p>
}

<p>Service state at @State render time: <span id="@($"service-{State}")">@PreserveService.Guid</span></p>

@* This section proves that state is only available during the first render and its gone afterwards. *@
@if(ExtraState != null)
{
    <button id="@($"button-{ExtraState}")" @onclick="DisplayExtraState">DisplayExtraState</button>
    @if(_extraStateAvailable == true)
    {
        <p>Extra state available: true</p>
        <p>Extra state: <span id="@($"extra-{ExtraState}")">@_extraState</span></p>
    }
    else if(_extraStateAvailable == null)
    {
        <p>Extra state available: unknown</p>
    }
    else
    {
        <p>Extra state available: false</p>
        <p>Extra state: <span id="@($"extra-{ExtraState}")">@_extraState</span></p>
    }
}

@code{
    [Parameter] public string State { get; set; }

    [Parameter] public string ExtraState { get; set; }

    private string _state = null;
    private string _extraState = null;
    private bool _restored;
    private bool? _extraStateAvailable;

    protected override void OnInitialized()
    {
        if (AppState.TryTakePersistedState(State, out var preserved))
        {
            _state = Encoding.UTF8.GetString(preserved);
            _restored = true;
        }
        else
        {
            _state = Guid.NewGuid().ToString();
            AppState.PersistState(State, Encoding.UTF8.GetBytes(_state));
            _extraState = Guid.NewGuid().ToString();
            if(ExtraState != null)
            {
                _extraStateAvailable = true;
                AppState.PersistState(ExtraState, Encoding.UTF8.GetBytes(_extraState));
            }
        }
    }

    public void DisplayExtraState()
    {
        if (AppState.TryTakePersistedState(ExtraState, out var extraState))
        {
            _extraStateAvailable = true;
            _extraState = Encoding.UTF8.GetString(extraState);
        }
        else
        {
            _extraStateAvailable = false;
            _extraState = Guid.NewGuid().ToString();
        }
    }
}
